package org.rugby.online.persistency;

import java.io.File;
import java.io.IOException;

import org.rugby.online.core.exception.RboException;
import org.rugby.online.core.exception.RboExceptionType;

/**
 * Class for file management
 * 
 * @author marseille
 */
public abstract class FileUtils {

	/**
	 * Method to create a directory into specified path
	 * 
	 * @param dirname
	 *            the directory name
	 * @param newdirpath
	 *            the path
	 */
	public static void makeDirIntoPath(String dirname, String newdirpath)
			throws RboException {

		File dir = new File(dirname + "/" + newdirpath);
		dir.mkdir();		
	}
	
	public static void createNewFileIntoPath(String persistencyPathForClass,
			String filename) throws RboException {
		
		File targetDir = new File(persistencyPathForClass);
		
		// directory does exists ?
		checkIfDirectoryExist(targetDir);
		
		// is it a directory ?
		checkIsDirectory(targetDir);
		
		File targetFile = new File(persistencyPathForClass + "/" + filename);
		
		// delete previous version
		boolean previousDeleted = targetFile.delete();
		try {
			targetFile.createNewFile();
			if (previousDeleted) {
				throw new RboException(RboExceptionType.INFO, "file " + filename + " already exists : deletion occured.");
			}
		} catch (IOException e) {
			throw new RboException(RboExceptionType.WARNING, "error creating " + filename + " :\n", e);
		}	
	}

	/**
	 * Method to check that a directory exists
	 * @param dir the directory to test
	 * @throws RboException when it does not exists
	 */
	private static void checkIfDirectoryExist(File dir) throws RboException {
		if (!dir.exists()) {
			throw new RboException(RboExceptionType.ERROR,
					"directory path does not exists.");
		}
	}
	
	/**
	 * Method to check that a directory exists
	 * @param dir the directory to test
	 * @throws RboException when it does not exists
	 */
	private static void checkIsDirectory(File dir) throws RboException {
		if (!dir.isDirectory()) {
			throw new RboException(RboExceptionType.ERROR, "directory path "
					+ dir.getPath() + " is not a directory.");
		}
	}



}
